<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>班级管理 - 管理后台</title>
    <link th:href="@{/admin/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/admin/css/bootstrap-icons.css}" rel="stylesheet">
    <link th:href="@{/admin/css/admin.css}" rel="stylesheet">
    <style>
        .create-class-form {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .table-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }
        .grade-badge {
            font-size: 0.8rem;
            padding: 4px 8px;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" th:href="@{/admin}">
                <i class="bi bi-gear-fill me-2"></i>口语练习管理后台
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" th:href="@{/}" target="_blank">
                    <i class="bi bi-box-arrow-up-right me-1"></i>前台页面
                </a>
                <form th:action="@{/api/v1/auth/logout}" method="post" class="d-inline">
                    <button type="submit" class="btn btn-outline-light btn-sm">
                        <i class="bi bi-box-arrow-right me-1"></i>退出登录
                    </button>
                </form>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 bg-light sidebar">
                <div class="position-sticky pt-3">
                    <ul class="nav nav-pills flex-column">
                        <li class="nav-item">
                            <a th:href="@{/admin}" class="nav-link">
                                <i class="bi bi-house-door me-2"></i>仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a th:href="@{/admin/users}" class="nav-link">
                                <i class="bi bi-people me-2"></i>用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a th:href="@{/admin/exam-papers}" class="nav-link">
                                <i class="bi bi-file-text me-2"></i>试卷管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a th:href="@{/admin/classes}" class="nav-link active">
                                <i class="bi bi-building me-2"></i>班级管理
                            </a>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- 主内容 -->
            <main class="col-md-10 ms-sm-auto px-md-4">
                <!-- 页面标题 -->
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="bi bi-building me-2"></i>班级管理
                    </h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="refreshClasses()">
                            <i class="bi bi-arrow-clockwise me-1"></i>刷新数据
                        </button>
                    </div>
                </div>

                <!-- 消息提示区域 -->
                <div id="messageArea"></div>

                <!-- 创建班级表单 -->
                <div class="create-class-form">
                    <h5><i class="bi bi-plus-circle me-2"></i>新增班级</h5>
                    <form id="createClassForm" onsubmit="createClass(event)">
                        <div class="row">
                            <div class="col-md-4">
                                <label for="gradeSelect" class="form-label">年级 <span class="text-danger">*</span></label>
                                <select class="form-select" id="gradeSelect" required>
                                    <option value="">请选择年级</option>
                                    <option value="1">一年级</option>
                                    <option value="2">二年级</option>
                                    <option value="3">三年级</option>
                                    <option value="4">四年级</option>
                                    <option value="5">五年级</option>
                                    <option value="6">六年级</option>
                                    <option value="7">七年级</option>
                                    <option value="8">八年级</option>
                                    <option value="9">九年级</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="classNameInput" class="form-label">班级名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="classNameInput" 
                                       placeholder="如: 1班、2班" required maxlength="50">
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="bi bi-plus-lg me-1"></i>创建班级
                                </button>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- 班级列表 -->
                <div class="table-container">
                    <div id="loadingIndicator" class="text-center p-4" style="display: none;">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2">加载班级数据中...</p>
                    </div>
                    
                    <div id="classesTableContainer">
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>ID</th>
                                        <th>年级</th>
                                        <th>班级名称</th>
                                        <th>学生人数</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="classesTableBody">
                                    <!-- 班级数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div id="emptyState" class="empty-state" style="display: none;">
                        <i class="bi bi-building display-1"></i>
                        <h4 class="mt-3">暂无班级数据</h4>
                        <p>点击上方"创建班级"按钮新增班级</p>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除班级</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="deleteModalBody">
                    确认要删除该班级吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn" onclick="executeDelete()">
                        <i class="bi bi-trash me-1"></i>删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script th:src="@{/admin/js/bootstrap.bundle.min.js}"></script>
    <script>
        let allClasses = [];
        let pendingDeleteId = null;
        let pendingDeleteName = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadClasses();
        });

        // 加载班级数据
        function loadClasses() {
            showLoading(true);
            
            fetch('/api/v1/classes')
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        allClasses = data.data || [];
                        renderClasses();
                    } else {
                        showMessage(data.message || '加载班级数据失败', 'danger');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('网络错误，请稍后重试', 'danger');
                })
                .finally(() => {
                    showLoading(false);
                });
        }

        // 创建班级
        function createClass(event) {
            event.preventDefault();
            
            const grade = document.getElementById('gradeSelect').value;
            const className = document.getElementById('classNameInput').value.trim();
            
            if (!grade || !className) {
                showMessage('请填写完整的班级信息', 'danger');
                return;
            }

            const submitBtn = document.querySelector('#createClassForm button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>创建中...';

            const requestData = {
                grade: parseInt(grade),
                className: className
            };

            fetch('/api/v1/classes', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    showMessage('班级创建成功！', 'success');
                    
                    // 清空表单
                    document.getElementById('gradeSelect').value = '';
                    document.getElementById('classNameInput').value = '';
                    
                    // 刷新列表
                    setTimeout(() => {
                        loadClasses();
                    }, 1000);
                } else {
                    showMessage(data.message || '班级创建失败', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('网络错误，请检查连接后重试', 'danger');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="bi bi-plus-lg me-1"></i>创建班级';
            });
        }

        // 删除班级
        function deleteClass(classId, className, studentCount) {
            pendingDeleteId = classId;
            pendingDeleteName = className;
            
            let modalBodyContent;
            if (studentCount > 0) {
                modalBodyContent = `
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        该班级下还有 <strong>${studentCount}</strong> 名学生，无法删除！
                    </div>
                    <p>请先将学生转移到其他班级后再删除。</p>
                `;
                document.getElementById('confirmDeleteBtn').style.display = 'none';
            } else {
                modalBodyContent = `
                    <p>确认要删除班级 <strong>"${className}"</strong> 吗？</p>
                    <p class="text-muted small">此操作不可撤销，请谨慎操作。</p>
                `;
                document.getElementById('confirmDeleteBtn').style.display = 'inline-block';
            }
            
            document.getElementById('deleteModalBody').innerHTML = modalBodyContent;
            new bootstrap.Modal(document.getElementById('deleteModal')).show();
        }

        // 执行删除
        function executeDelete() {
            if (!pendingDeleteId) return;

            const confirmBtn = document.getElementById('confirmDeleteBtn');
            confirmBtn.disabled = true;
            confirmBtn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>删除中...';

            fetch(`/api/v1/classes/${pendingDeleteId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                
                if (data.code === 0) {
                    showMessage(`班级 "${pendingDeleteName}" 删除成功！`, 'success');
                    
                    // 刷新列表
                    setTimeout(() => {
                        loadClasses();
                    }, 1000);
                } else {
                    showMessage(data.message || '删除失败，请重试', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                showMessage('网络错误，请检查连接后重试', 'danger');
            })
            .finally(() => {
                confirmBtn.disabled = false;
                confirmBtn.innerHTML = '<i class="bi bi-trash me-1"></i>删除';
                pendingDeleteId = null;
                pendingDeleteName = null;
            });
        }

        // 刷新班级列表
        function refreshClasses() {
            loadClasses();
        }

        // 渲染班级表格
        function renderClasses() {
            const tbody = document.getElementById('classesTableBody');
            const emptyState = document.getElementById('emptyState');
            const tableContainer = document.getElementById('classesTableContainer');

            if (allClasses.length === 0) {
                tableContainer.style.display = 'none';
                emptyState.style.display = 'block';
                return;
            }

            tableContainer.style.display = 'block';
            emptyState.style.display = 'none';

            tbody.innerHTML = allClasses.map(classInfo => `
                <tr>
                    <td><strong>#${classInfo.id}</strong></td>
                    <td>
                        <span class="badge grade-badge bg-primary">
                            ${getGradeText(classInfo.grade)}
                        </span>
                    </td>
                    <td><strong>${classInfo.className}</strong></td>
                    <td>
                        <span class="badge bg-info">
                            <i class="bi bi-people me-1"></i>${classInfo.studentCount || 0}人
                        </span>
                    </td>
                    <td>
                        <button type="button" class="btn btn-danger btn-sm" 
                                onclick="deleteClass(${classInfo.id}, '${classInfo.className}', ${classInfo.studentCount || 0})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 显示加载状态
        function showLoading(show) {
            const loadingIndicator = document.getElementById('loadingIndicator');
            const tableContainer = document.getElementById('classesTableContainer');
            
            if (show) {
                loadingIndicator.style.display = 'block';
                tableContainer.style.display = 'none';
            } else {
                loadingIndicator.style.display = 'none';
                tableContainer.style.display = 'block';
            }
        }

        // 显示消息
        function showMessage(message, type = 'success') {
            const messageArea = document.getElementById('messageArea');
            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            
            messageArea.innerHTML = `
                <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                    <i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            
            // 自动隐藏成功消息
            if (type === 'success') {
                setTimeout(() => {
                    const alert = messageArea.querySelector('.alert');
                    if (alert) {
                        const bsAlert = new bootstrap.Alert(alert);
                        bsAlert.close();
                    }
                }, 3000);
            }
        }

        // 辅助函数
        function getGradeText(grade) {
            const gradeNames = {
                1: '一年级',
                2: '二年级',
                3: '三年级',
                4: '四年级',
                5: '五年级',
                6: '六年级',
                7: '七年级',
                8: '八年级',
                9: '九年级'
            };
            return gradeNames[grade] || `${grade}年级`;
        }

        function formatDateTime(dateTime) {
            if (!dateTime) return '未知';
            
            try {
                const date = new Date(dateTime);
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            } catch (e) {
                return '无效日期';
            }
        }
    </script>
</body>
</html>